/**
 * 
 */
package com.google.code.maven.plugin.http.client.config;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

import com.google.code.maven.plugin.http.client.Credentials;
import com.google.code.maven.plugin.http.client.Request;
import com.google.code.maven.plugin.http.client.RequestParameter;

/**
 * RequestConfiguration
 * 
 * @author Nadim Benabdenbi
 * @version 1.0
 * @since JDK1.6
 */
public class RequestConfiguration extends Request implements ConfigurationBean<Request> {

	protected static final AtomicInteger id = new AtomicInteger();

	/**
	 * @parameter
	 */
	private RequestParameterConfiguration parameters[];
	/**
	 * @parameter
	 */
	private CredentialsConfiguration credentials;

	/**
	 * @parameter
	 */
	private FormCredentialsConfiguration formCredentials;

	public Request build(DefaultListableBeanFactory factory) {
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(Request.class);
		String beanId = Credentials.class.getSimpleName() + id.incrementAndGet();
		builder.addPropertyValue("url", getUrl());
		builder.addPropertyValue("method", getMethod());
		builder.addPropertyValue("credentials", credentials == null ? null : credentials.build(factory));
		builder.addPropertyValue("formCredentials", formCredentials == null ? null : formCredentials.build(factory));
		if (parameters != null) {
			RequestParameter parameters[] = new RequestParameter[this.parameters.length];
			for (int i = 0; i < this.parameters.length; i++) {
				parameters[i] = this.parameters[i].build(factory);
			}
			builder.addPropertyValue("parameters", parameters);
		}
		factory.registerBeanDefinition(beanId, builder.getBeanDefinition());
		return factory.getBean(beanId, Request.class);
	}

	/**
	 * @return the parameters
	 */
	public RequestParameterConfiguration[] getParameters() {
		return parameters;
	}

	/**
	 * @param parameters the parameters to set
	 */
	public void setParameters(RequestParameterConfiguration[] parameters) {
		this.parameters = parameters;
	}

	/**
	 * @return the credentials
	 */
	public CredentialsConfiguration getCredentials() {
		return credentials;
	}

	/**
	 * @param credentials the credentials to set
	 */
	public void setCredentials(CredentialsConfiguration credentials) {
		this.credentials = credentials;
	}

	/**
	 * @return the formCredentials
	 */
	public FormCredentialsConfiguration getFormCredentials() {
		return formCredentials;
	}

	/**
	 * @param formCredentials the formCredentials to set
	 */
	public void setFormCredentials(FormCredentialsConfiguration formCredentials) {
		this.formCredentials = formCredentials;
	}

}
